package com.aikg.kgrag_java.controller;

import cn.hutool.core.util.StrUtil;
import com.aikg.kgrag_java.common.Result;
import com.aikg.kgrag_java.pojo.entity.FileStorage;
import com.aikg.kgrag_java.pojo.vo.FileVo;
import com.aikg.kgrag_java.service.FileStorageService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping()
public class FileUploadController {

    @Resource
    private FileStorageService fileStorageService;

    /**
     * 处理文件上传,用于存储文件
     *
     *  TODO 是在OCR处理之前的时候需要调用
     *
     * @param uploadFile 上传的文件
     * @param projectId     领域
     * @param knowledgeDBName 知识库
     * @param request    HTTP 请求对象
     * @return 返回上传结果
     */
    @PostMapping("/addDocs")
    public Result uploadFile(@RequestParam("files") MultipartFile uploadFile,
                             @RequestParam("projectId") String projectId,
                             @RequestParam("knowledgeDB_name") String knowledgeDBName,
                             HttpServletRequest request) {
        if(uploadFile == null || StrUtil.isBlank(projectId) || StrUtil.isBlank(knowledgeDBName)){
            return Result.buildErrorResult("参数不能为空");
        }
        return fileStorageService.uploadFile(uploadFile, Integer.valueOf(projectId), knowledgeDBName, request);
    }

    /**
     * 获取每个knowledgedb下文件数量
     * @param projectId
     * @return
     */
    @GetMapping("/get_knowledgedbs_file_number")
    public Result getKnowledgeDBsFileNumber(@RequestParam("projectId") Integer projectId){
        if(projectId == null){
            return Result.buildErrorResult("projectId不能为空");
        }
        Result knowledgeDBsFileNumber = fileStorageService.getKnowledgeDBsFileNumber(projectId);
        return knowledgeDBsFileNumber;
    }

    /**
     * 获取某 project下文件总数
     * @param projectId
     * @return
     */
    @GetMapping("/get_files_number")
    public Result getFilesNumber(@RequestParam("projectId") Integer projectId){
        if(projectId == null){
            return Result.buildErrorResult("projectId不能为空");
        }
        // 使用 QueryWrapper 构建查询条件，查询项目 ID 对应的文件数量
        QueryWrapper<FileStorage> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("project_id", projectId);
        long count = fileStorageService.count(queryWrapper);
        return Result.buildSuccessResultWithData(count);
    }

    /**
     * 删除指定知识库中的单个文档
     * @param projectId
     * @param knowledgeDB_name
     * @param filename
     * @return
     */
    @PostMapping("/deleteDoc")
    public Result deleteDoc(@RequestParam int projectId,
                            @RequestParam String knowledgeDB_name,
                            @RequestParam String filename) {
        if(projectId <= 0 || StrUtil.isBlank(knowledgeDB_name) || StrUtil.isBlank(filename)){
            return Result.buildErrorResult("参数无效");
        }
        boolean b = fileStorageService.deleteKnowledgeDBFile(projectId, knowledgeDB_name, filename);
        if(b){
            Map<String, String> map = new HashMap<>();
            map.put("文件", filename);
            map.put("知识库", knowledgeDB_name);  // 现在可以正常执行
            return Result.buildSuccessResultWithData(map);
        }else{
            return Result.buildErrorResult("删除失败");
        }
    }

    /**
     * 获取指定知识库下所有文档名称
     * @param projectId 项目ID
     * @param knowledgeDB 知识库名称
     * @return 返回包含文档名称的成功结果
     */
    @GetMapping("/KnowledgeDB/getDocs")
    public Result getDocs(@RequestParam int projectId, @RequestParam String knowledgeDB) {
        try {
            // 参数校验
            if (projectId <= 0 || StrUtil.isBlank(knowledgeDB)) {
                return Result.buildErrorResult("项目ID或知识库ID无效");
            }

            // 调用服务层获取文件列表
            List<FileVo> files = fileStorageService.getFileByProjectIdAndKnowledgeDB(projectId, knowledgeDB);

            // 判断文件列表是否为空
            if (files == null || files.isEmpty()) {
                return Result.buildErrorResult("没有找到相关文档");
            }

            // 返回成功结果
            return Result.buildSuccessResultWithData(files);

        } catch (Exception e) {
            return Result.buildErrorResult("服务器错误，请稍后重试");
        }
    }

}
